<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="formRef"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<el-form-item class="flex-row-container">
					<el-select
						v-model="queryData.userType"
						:placeholder="$t('common.please_choose')"
						style="width: 110px"
						@change="handletypChange"
					>
						<el-option label="代理账号" :value="2"></el-option>
						<el-option label="全部总代" :value="3"></el-option>
					</el-select>
					<el-input
						v-model="queryData.userName"
						class="input-with-select"
						:placeholder="$t('common.please_enter')"
						clearable
						size="medium"
						:disabled="queryData.userType === 3"
						style="width: 200px"
						@input="forceUpdate"
					></el-input>
				</el-form-item>
				<el-form-item
					label="账单周期"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.billEndDate"
						placeholder="请选择"
						style="width: 350px"
					>
						<el-option
							v-for="item in billDateList"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="对账结果">
					<el-select
						v-model="queryData.matchResult"
						:placeholder="'全部'"
						style="width: 110px"
					>
						<el-option label="匹配失败" :value="0"></el-option>
						<el-option label="匹配成功" :value="1"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item class="flex-row-container">
					<el-button
						type="primary"
						icon="el-icon-search"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						type="warning"
						icon="el-icon-download"
						size="medium"
						:loading="exportBtnLoading"
						@click="handleExportExcel"
					>
						{{ $t('common.export') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				ref="elTable"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:max-height="tableHeight"
				:data="tableData"
				v-bind="$attrs"
				v-on="$listeners"
				:header-cell-style="getRowClass"
				highlight-current-row
			>
				<el-table-column
					v-for="(item, index) in newCol"
					:key="'column_' + index"
					:prop="newCol[index].prop"
					:align="item.alignCenter"
					:label="item.label"
					:min-width="item.minWidth"
					:fixed="item.isFixed"
					:sortable="item.isSortColumn"
					:show-overflow-tooltip="item.isShowTip"
				>
					<template slot="header">
						<span v-if="item.itemTipContent">
							{{ item.label }}
							<el-tooltip
								class="item"
								effect="dark"
								:content="item.itemTipContent"
								placement="top-start"
							>
								<i class="el-icon-question"></i>
							</el-tooltip>
						</span>
						<span v-else>
							{{ item.label }}
						</span>
					</template>
					<template slot-scope="{ row, $index }">
						<template v-if="item.slot === 'serialNumber'">
							{{ $index + 1 }}
						</template>
						<div v-if="item.slot === 'numberSolt'">
							<el-link
								type="primary"
								@click="dialogData(row, item)"
							>
								{{
									handleNumber(
										'USDT',
										row[newCol[index].prop],
										2,
										true
									)
								}}
							</el-link>
						</div>
						<!-- 账号类型渲染 -->
						<span v-if="item.slot === 'accountTypeSolt'">
							<p>
								{{ typeFilter(row[item.prop], 'accountType') }}
							</p>
						</span>
						<div v-if="item.slot === 'matchResultSolot'">
							<p
								:style="{
									color: row[item.prop] === 0 ? 'red' : ''
								}"
							>
								{{
									row[item.prop] === 0
										? '匹配失败'
										: '匹配成功'
								}}
							</p>
						</div>
						<div v-if="item.slot === 'defaultSolt'">
							<span>
								{{
									row[newCol[index].prop] !== undefined &&
									row[newCol[index].prop] !== null
										? row[newCol[index].prop]
										: '-'
								}}
							</span>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				class="pageValue"
				:current-page.sync="pageNum"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size.sync="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>

		<component
			v-if="amountDialog.visible"
			:is="amountDialog.name"
			v-model="amountDialog.visible"
			:row="amountDialog.row"
		/>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { getColumns } from './components/columns'
import MainContent from '@/components/MainContent/index.vue'
import PeriodSholdSentRebateDialog from './components/periodSholdSentRebateDialog'
import PeriodRealHairRebateDialog from './components/periodRealHairRebateDialog'
import PeriodRejectRebateDialog from './components/periodRejectRebateDialog'

export default {
  components: {
    MainContent,
    PeriodSholdSentRebateDialog,
    PeriodRealHairRebateDialog,
    PeriodRejectRebateDialog
  },
  mixins: [list],
  data() {
    return {
      dayjs,
      tableHeight: 480,
      otherDependenComponents: [],
      queryData: {
        userType: 3,
        userName: '',
        billEndDate: '',
        matchResult: undefined
      },
      tableData: [],
      billDateList: [],
      loading: false,
      exportBtnLoading: false,
      amountDialog: {
        name: '',
        visible: false,
        row: {}
      }
    }
  },
  created() {
    this.newCol = getColumns()
  },
  mounted() {
    this.getSettlementBillTimeList()
  },
  methods: {
    handletypChange() {
      this.$nextTick(() => {
        if (this.queryData.userType === 3) {
          this.queryData.userName = undefined
        }
      })
    },
    dialogData(row, col) {
      const dialogNames = {
        shouldRebateAmount: 'PeriodSholdSentRebateDialog',
        realRebateAmount: 'PeriodRealHairRebateDialog',
        invalidRebateAmount: 'PeriodRejectRebateDialog'
      }
      this.amountDialog = {
        name: dialogNames[col.prop],
        row: row,
        visible: true
      }
    },
    forceUpdate(value) {
      this.$forceUpdate()
      this.queryData.userName = this.queryData.userName.replace(
        /[^A-Za-z0-9]/g,
        ''
      )
    },
    getSettlementBillTimeList() {
      this.loading = true
      const params = {
        pageNum: 1,
        pageSize: 200,
        periodType: 6
      }
      this.$api
        .proxyTeamBillPeriod(params)
        .then((res) => {
          this.loading = false
          if (res?.code === 200) {
            const { record } = res?.data
            this.billDateList = record
              .filter(item => item.billType != 0)
              .map(
                (item, index) => {
                  const startTime = dayjs(String(item.periodStDate)).format('YYYY-MM-DD') + ' 00:00:00'
                  const endTime = dayjs(String(item.periodEnDate)).format('YYYY-MM-DD') + ' 23:59:59'
                  return {
                    code: index,
                    description: `${startTime} 至 ${endTime}`,
                    periodStDate: item.periodStDate,
                    periodEnDate: item.periodEnDate,
                    periodStStr: startTime,
                    periodEnStr: endTime
                  }
                }
              )
            this.queryData.billEndDate = this.billDateList.length > 1 ? 0 : ''

            this.loadData()
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    loadData() {
      if (!this.billDateList.length) return

      const params = {
        ...this.queryData,
        ...this.getParams()

      }
      if (params.userType === 3) {
        delete params.userName
      }
      params['accountType'] = params.userType
      params.cycleEndDate = this.billDateList[this.queryData.billEndDate].periodEnDate
      params.cycleStartDate = this.billDateList[this.queryData.billEndDate].periodStDate
      delete params.billEndDate
      delete params.userType
      this.loading = true
      this.$api
        .reportCreditBillReconciliationReconciliationListPage(params)
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            this.tableData = []
            this.tableData = res?.data?.record || []
            this.total = res?.data?.totalRecord || 0
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    search() {
      this.pageNum = 1
      this.loadData()
    },
    reset() {
      this.pageNum = 1
      this.queryData = {
        billEndDate: this.billDateList.length > 1 ? 0 : '',
        userType: 3,
        userName: ''
      }

      this.loadData()
    },
    handleExportExcel() {
      const params = {
        ...this.queryData
      }
      if (params.userType === 3) {
        delete params.userName
      }
      params['accountType'] = params.userType
      params.cycleEndDate = this.billDateList[this.queryData.billEndDate].periodEnDate
      params.cycleStartDate = this.billDateList[this.queryData.billEndDate].periodStDate
      delete params.billEndDate
      delete params.userType
      this.exportBtnLoading = true
      this.exportExcelPublic({
        api: 'reportCreditBillReconciliationReconciliationExport',
        params
      }).finally(() => {
        this.exportBtnLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tips-box {
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -12px;
}
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
.input-with-select {
	width: 110px;
}
.ptop {
	padding-top: 2px;
	margin-left: 10px;
}
::v-deep .el-icon-question:after {
	font-size: 16px;
	margin-left: 0;
}
</style>
